package dk.itu.samd.group2.tagapastry.messages;

import java.io.IOException;

import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

import rice.p2p.commonapi.Endpoint;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;
import rice.p2p.commonapi.rawserialization.InputBuffer;
import rice.p2p.commonapi.rawserialization.OutputBuffer;

public class UpdateSizeMsg extends TagapastryMsg {

	public static final short TYPE = 10;
	private static final long serialVersionUID = TYPE;
	private final int sizeDelta;
	
	public UpdateSizeMsg(Tag tag, NodeHandle sender, int sizeDelta) {
		super(tag, sender);
		this.sizeDelta = sizeDelta;
	}
	
	public UpdateSizeMsg(InputBuffer buf, Endpoint endpoint) throws IOException {
		super(buf, endpoint);
		this.sizeDelta = buf.readInt();
	}
	
	public int getSize() {
		int size = super.getSize();
		return size + sizeDelta;
	}

	@Override
	public void execute(TagapastryImpl taga) {
		Index index = taga.getIndex(tag);
		if(index == null) {
			System.out.println("Update msg failed with size: " + this.getSize());
			taga.getClient().getMsgCollector().incBytesSent(this);
			return;
		}
		index.addToSizeOfSubtree(sizeDelta);
	}
	
	@Override
	public void serialize(OutputBuffer buf) throws IOException {
		super.serialize(buf);
		buf.writeInt(sizeDelta);
	}

	@Override
	public Id getRecepientId() {
		return tag.getId();
	}

	@Override
	public short getType() {
		// TODO Auto-generated method stub
		return TYPE;
	}

	@Override
	public String toString() {
		return super.toString() + ", delta: " + sizeDelta + " }";
	}
	

}
